<?php

namespace addons\shopro\job;

use addons\shopro\service\Wallet as WalletService;
use app\admin\model\RechargeCorrectLog;
use app\admin\model\shopro\user\User;
use think\queue\Job;
use think\Db;
use think\exception\HttpResponseException;
use addons\shopro\service\commission\Agent as AgentService;

/**
 * 充正任务
 */
class RechargeCorrect extends BaseJob
{

    /**
     * 充正
     */
    public function index(Job $job, $payload)
    {
        try {
            $id=$payload["user_id"];
            $Ok_redis_key = 'rechargeCorrectOk|user';
            $res=redis_cache()->SISMEMBER($Ok_redis_key,$id);
            if(!$res){
                Db::transaction(function () use ($id)  {
                    $this->rechargeCorrect($id);
                });
            }
            $job->delete();
        } catch (HttpResponseException $e) {
            $data = $e->getResponse()->getData();
            $message = $data ? ($data['msg'] ?? '') : $e->getMessage();
            format_log_error($e, 'RechargeCorrect.HttpResponseException', $message);
        } catch (\Exception $e) {
            format_log_error($e, 'RechargeCorrect');
        }
    }
    /**
     * 新充正
     */
    public function index1(Job $job, $payload)
    {
        try {
            $data = redis_cache("rectification_data");
            $lockVal=md5(time().rand("000000","999999"));
            $recharge_lock=redis_cache()->setnx('recharge_lock',$lockVal);
            if($recharge_lock){
                if ($data) {
                    $data = json_decode($data, true);
                    $count = 0;
                    foreach ($data as $k => $v) {
                        $user = User::where(["id" => $v])->find();
                        if (!empty($user)) {
                            if ($user["payment_goods"] < 0) {
                                Db::transaction(function () use ($v,$user) {
                                    WalletService::autorechargePayment($v);
                                });
                            }
                        }
                        unset($data[$k]);
                        $count++;
                        if ($count > 99) {
                            redis_cache("rectification_data", json_encode($data), 3600);
                            redis_cache()->delete('recharge_lock');
                            $job->delete();
                            exit;
                        }
                    }
                }
                redis_cache()->delete('recharge_lock');
                redis_cache("rectification_data", null);
                $job->delete();
            }
        } catch (HttpResponseException $e) {
            redis_cache()->delete('recharge_lock');
            $data = $e->getResponse()->getData();
            $message = $data ? ($data['msg'] ?? '') : $e->getMessage();
            $job->delete();
            format_log_error($e, 'RechargeCorrect.HttpResponseException', $message);
        } catch (\Exception $e) {
            redis_cache()->delete('recharge_lock');
            format_log_error($e, 'RechargeCorrect');
        }
    }
    public function rechargeCorrect($id)
    {
        $redis_key = 'rechargeCorrect|user';
        $user=User::where(["id"=>$id])->find();
        if(!empty($user)){
            if(!empty($user["parent_user_id"])){
                //如果上级id不存在与上级id集合中 ---追加到上级id集合中
                $res=redis_cache()->SISMEMBER($redis_key,$user['parent_user_id'] );
                if(!$res){
                    redis_cache()->sAdd($redis_key,$user['parent_user_id'] );
                    //如果上级id不存在与上级id集合中 ---追加到队列
                    \think\Queue::push('\addons\shopro\job\RechargeCorrect@index', [
                        'user_id' => $user['parent_user_id']
                    ], 'shopro');
                }
            }
            if($user["payment_goods"]<0){
                WalletService::autorechargePayment($id);
            }
            $Ok_redis_key = 'rechargeCorrectOk|user';
            redis_cache()->sAdd($Ok_redis_key,$id);
            //如果当前执行的id在上级id集合里--移除上级集合id
            /*$res=redis_cache()->SISMEMBER($redis_key,$id);
            if($res){
                redis_cache()->sRem($redis_key,$id );
            }*/
        }
    }

    /*public function rechargeCorrect($id)
    {
        $user_ids=User::alias("user")
            ->join("user t2","user.id=t2.parent_user_id","left")
            ->where("t2.id is null")
            ->column("user.id");
        if(!empty($user_ids)){
            $user = User::whereIn("id",$user_ids)->select();//查找最底层用户
            if (!empty($user)) {
                foreach ($user as $user) {
                    WalletService::autorechargePayment($user["id"]);
                }
            }
        }
    }*/

}
